# coding: utf-8
import string
import time
import random
import hashlib
import urllib2
import json

LEANID = 'm3vGPBDTLcIBYncljScwWGaQ'
LEANKEY = 'o6PmgVg0yHr2cwHMUBctNzvb'

WXAPPID = 'wx147a7583c9622a1b'
MCH_ID = '1311531301'
PAYKEY = 'zSKBivc46GdAOe72JTnfuw1QHUIWrkmD'
DATAXML = u'''<xml>
<sign><![CDATA[E1EE61A91C8E90F299DE6AE075D60A2D]]></sign>
<mch_billno><![CDATA[0010010404201411170000046545]]></mch_billno>
<mch_id><![CDATA[888]]></mch_id>
<wxappid><![CDATA[wxcbda96de0b165486]]></wxappid>
<send_name><![CDATA[send_name]]></send_name>
<re_openid><![CDATA[onqOjjmM1tad-3ROpncN-yUfa6uI]]></re_openid>
<total_amount><![CDATA[200]]></total_amount>
<total_num><![CDATA[1]]></total_num>
<wishing><![CDATA[恭喜发财]]></wishing>
<client_ip><![CDATA[127.0.0.1]]></client_ip>
<act_name><![CDATA[新年红包]]></act_name>
<remark><![CDATA[新年红包]]></remark>
<nonce_str><![CDATA[50780e0cca98c8c8e814883e5caa672e]]></nonce_str>
</xml>'''
SUCCESSXML = u'''<xml>
  <return_code><![CDATA[SUCCESS]]></return_code>
  <return_msg><![CDATA[OK]]></return_msg>
</xml>'''




def sendredpack():
    posturl = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack'
    openid = 'testopenid'
    send_name = u'音速风暴路轨赛车'
    wishing = u'红包祝福语测试'
    act_name = u'测试活动名'
    remark = u'测试备注'
    data = getpostdata(100, openid, send_name, wishing, act_name, remark)
    
    return data
    
def getpostdata(total_amount, openid, send_name, wishing, act_name, remark):
    data = {
        'mch_id': MCH_ID,
        'mch_billno': '{0}{1}{2}'.format(
            MCH_ID, time.strftime('%Y%m%d%H%M%S'), random.randint(1000, 10000)),
        'wxappid': WXAPPID,
        'send_name': send_name,
        're_openid': openid,
        'total_amount': total_amount,
        'total_num': 1,
        'wishing': wishing,
        'client_ip': '192.168.1.1',
        'act_name': act_name,
        'remark': remark,
    }
    data['mch_billno'] = '1311531301201603031639228088' # for test
    data['nonce_str'] = random_string()
    data['sign'] = sign(data)
    
    data = data_jsontoxml(data)
    
    return data
    
def data_jsontoxml(data):
    xml = '<xml>'
    for t in sorted(data):
        xml += '\n<{0}><![CDATA[{1}]]></{0}>'.format(t, data[t])
    xml += '\n</xml>'
    
    return xml
    
def sign(data):
    stringA = u''
    for k in sorted(data):
        stringA += u'{0}={1}&'.format(k, data[k])
    stringSignTemp = stringA + 'key=' + PAYKEY
    # print stringSignTemp
    sign = hashlib.md5(stringSignTemp.encode('utf-8')).hexdigest().upper()
    
    return sign

def getwepayurl(product_id):
    url = 'weixin://wxpay/bizpayurl?appid=%(appid)s&mch_id=%(mch_id)s&nonce_str=%(nonce_str)s&product_id=%(product_id)s&time_stamp=%(time_stamp)s&sign=%(sign)s'
    data = {
        'appid': WXAPPID,
        'mch_id': MCH_ID,
        'product_id': product_id,        
    }
    data['nonce_str'] = random_string(32)
    data['time_stamp'] = int(time.time())
    data['sign'] = sign(data)
    
    url = url % data
    return url
    
def createOrder(product_id, openid, total_fee=1, notify_url='http://m.top-racer.com/wechatpay/success', attach=None, body='nosetting'):
    url = 'https://api.mch.weixin.qq.com/pay/unifiedorder'
    import sys
    reload(sys)
    sys.setdefaultencoding('utf8')
    data = {
        'appid': WXAPPID,
        'mch_id': MCH_ID,
        'body': body,
        'out_trade_no': '{0}{1}'.format(time.strftime('%Y%m%d%H%M%S'), random.randint(1000, 10000)),
        'total_fee': total_fee,
        # 'spbill_create_ip': '192.168.1.1',
        'notify_url': notify_url,
        'trade_type': 'NATIVE',
        'openid': openid,
        'product_id': product_id,
    }
    if attach:
        data['attach'] = attach
    data['nonce_str'] = random_string(32)
    data['sign'] = sign(data)    
    savelog(data, 'WepayCreateorder')
    data = data_jsontoxml(data)
    ret = urllib2.urlopen(url, data).read()

    return ret
    
def savelog(data, logname):
    from leancloud import Object
    log = Object.extend(logname)()
    for t in data:
        log.set(t, data[t])
    log.save()
    
def payreturn(prepay_id, fail=False, failmsg='FaildMsg'):
    import sys
    reload(sys)
    sys.setdefaultencoding('utf8')    
    if fail:
        data = {
            'return_code': 'SUCCESS',
            'err_code_des': failmsg or 'FaildMsg',
            'result_code': 'FAIL'
        }
        return data_jsontoxml(data)
    else:
        data = {
            'return_code': 'SUCCESS', 
            'appid': WXAPPID,
            'mch_id': MCH_ID,
            'prepay_id': prepay_id, 
            'result_code': 'SUCCESS' if not fail else 'FAIL',
        }
    # if fail:
        # data['err_code_des'] = failmsg
    data['nonce_str'] = random_string(32)
    data['sign'] = sign(data)
    data = data_jsontoxml(data)
    return data
    
def random_string(length=16):
    rule = string.ascii_letters + string.digits
    rand_list = random.sample(rule, length)
    return ''.join(rand_list)
    
def short_url(l_url):
    url = 'https://api.mch.weixin.qq.com/tools/shorturl'
    data = {
        'appid': WXAPPID,
        'mch_id': MCH_ID,
        'long_url': l_url,
    }
    data['nonce_str'] = random_string(32)
    data['sign'] = sign(data)
    data = data_jsontoxml(data)
    ret = urllib2.urlopen(url, data).read()
    
    return ret
    
def orderquery(transaction_id=None, out_trade_no=None):
    url = 'https://api.mch.weixin.qq.com/pay/orderquery'
    if not transaction_id and not out_trade_no:
        return
    data = {
        'appid': WXAPPID,
        'mch_id': MCH_ID,
    }
    if transaction_id:
        data['transaction_id'] = transaction_id
    else:
        data['out_trade_no'] = out_trade_no
    data['nonce_str'] = random_string(32)
    data['sign'] = sign(data)
    data = data_jsontoxml(data)
    ret = urllib2.urlopen(url, data).read()
    
    return ret
        

if __name__ == '__main__': 
    import leancloud
    leancloud.init(LEANID, LEANKEY)
    # data = createOrder('123456', 'ohCrcvlQMzCovAxALwzdNOs8yNf8', body=u'哈哈')
    # print data
    # data = payreturn('asdf', True, u'你好吗？')

    # url = getwepayurl(1001)
    # open('pay_native_url.txt', 'w').write(url)